﻿using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace BloodApp.Common
{
    public static class AESService
    {
        private static byte[] key = Encoding.UTF8.GetBytes("1234567890123456"); // 16字节密钥，AES-128
        private static byte[] iv = Encoding.UTF8.GetBytes("1234567890123456"); // 16字节IV（初始化向量）

        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainText">原数据</param>
        /// <returns>加密数据</returns>
        public static string EncryptString(string plainText)
        {
            // 创建AES实例
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV = iv;
                // 创建加密器
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // 创建内存流和加密写入流
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            // 写入数据并加密
                            swEncrypt.Write(plainText);
                        }
                        // 返回加密后的字节数组转换为Base64字符串
                        return Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
            }
        }

        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">加密数据</param>
        /// <returns>原数据</returns>
        public static string DecryptString(string cipherText)
        {
            // 将Base64字符串转换回字节数组
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV = iv;
                // 创建解密器
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // 创建内存流和解密读取流
                using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            // 返回解密后的字符串
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}
